package groupb6.shopsystem.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import groupb6.shopsystem.config.AlipayConfig;
import groupb6.shopsystem.util.response.UniversalResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/alipay")
public class PayController {


    @GetMapping("/toPay")
    public UniversalResponse<String> toPay(String orderid, String price, String title) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.url, AlipayConfig.appId, AlipayConfig.privateKey, AlipayConfig.format, null, AlipayConfig.alipayPublicKey, AlipayConfig.signType);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.returnUrl);
        alipayRequest.setNotifyUrl(AlipayConfig.notifyUrl);

        try {
            //发送请求参数 orderid 订单id，price表示价格，title表示订单标题
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderid + "\","
                    + "\"total_amount\":\"" + price + "\","
                    + "\"subject\":\"" + title+ "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result;
            result = alipayClient.pageExecute(alipayRequest).getBody();

            System.out.println("*********************\n返回结果为：" + result);
            return new UniversalResponse<>(1000, "支付成功", result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return new UniversalResponse<>(1001, "pay错误", "");
        }
    }
}
